package com.client;

import NinetyNine.NinetyNineMessage;
import javax.jms.Message;
import javax.swing.JFrame;

import com.client.Register;
import com.server.NinetyNineGameBeanRemote;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
//import client.GameLobby;
import javax.jms.*;
import javax.naming.*;
import java.io.*;

/**
 *
 * @author Emma
 */
public class WelcomePage extends javax.swing.JFrame {

    static NinetyNineGameBeanRemote beanRemote;
    static int uid;
    static String uname;
    static WelcomePage wp = null;

    GameLobby gl = null;
    
    static Context                 jndiContext = null;
    static TopicConnectionFactory  topicConnectionFactory = null;
    static TopicConnection         topicConnection = null;
    static TopicSession            topicSession = null;
    static Topic                   topic = null;
    static TopicSubscriber         topicSubscriber = null;

    /** Creates new form MainPageJFrame */
    public WelcomePage() throws NamingException {
      
        initComponents();
        errorNotification.setText(" ");
       //errorNotification.setVisible(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        loginPanel = new javax.swing.JPanel();
        username = new javax.swing.JLabel();
        password = new javax.swing.JLabel();
        usernameTextField = new javax.swing.JTextField();
        logInButton = new javax.swing.JButton();
        passwordTextField = new javax.swing.JPasswordField();
        errorNotification = new javax.swing.JLabel();
        registerPanel = new javax.swing.JPanel();
        sloganTextField = new javax.swing.JTextField();
        RegisterButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");

        loginPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Welcome to Ninety-nine!", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("SimSun", 1, 18), new java.awt.Color(0, 153, 153))); // NOI18N

        username.setText("username");

        password.setText("password");

        usernameTextField.setNextFocusableComponent(passwordTextField);

        logInButton.setText("Log in");
        logInButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                logInButtonMouseClicked(evt);
            }
        });
        logInButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logInButtonActionPerformed(evt);
            }
        });

        passwordTextField.setNextFocusableComponent(logInButton);

        errorNotification.setText("Username password didn't match");

        javax.swing.GroupLayout loginPanelLayout = new javax.swing.GroupLayout(loginPanel);
        loginPanel.setLayout(loginPanelLayout);
        loginPanelLayout.setHorizontalGroup(
            loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginPanelLayout.createSequentialGroup()
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(loginPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(username)
                            .addComponent(password))
                        .addGap(31, 31, 31)
                        .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(passwordTextField)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)))
                    .addGroup(loginPanelLayout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(errorNotification))
                    .addGroup(loginPanelLayout.createSequentialGroup()
                        .addGap(130, 130, 130)
                        .addComponent(logInButton)))
                .addContainerGap(111, Short.MAX_VALUE))
        );
        loginPanelLayout.setVerticalGroup(
            loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginPanelLayout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(username)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(password)
                    .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(errorNotification)
                .addGap(18, 18, 18)
                .addComponent(logInButton)
                .addGap(19, 19, 19))
        );

        registerPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        sloganTextField.setBackground(new java.awt.Color(204, 204, 204));
        sloganTextField.setText("New to Ninety-nine?Join us NOW!");

        RegisterButton.setText("Register");
        RegisterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegisterButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout registerPanelLayout = new javax.swing.GroupLayout(registerPanel);
        registerPanel.setLayout(registerPanelLayout);
        registerPanelLayout.setHorizontalGroup(
            registerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(registerPanelLayout.createSequentialGroup()
                .addGroup(registerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(registerPanelLayout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(sloganTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(registerPanelLayout.createSequentialGroup()
                        .addGap(125, 125, 125)
                        .addComponent(RegisterButton)))
                .addContainerGap(118, Short.MAX_VALUE))
        );
        registerPanelLayout.setVerticalGroup(
            registerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(registerPanelLayout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(sloganTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(RegisterButton)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(loginPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(registerPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(loginPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(registerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void logInButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logInButtonMouseClicked

    }//GEN-LAST:event_logInButtonMouseClicked

    private void logInButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logInButtonActionPerformed

        uname = usernameTextField.getText();

        uid = beanRemote.login(usernameTextField.getText(), new String(
                passwordTextField.getPassword()));
        
        if (uid == -1) {
            System.err.println("Login Failed");
          //  errorNotification.setVisible(true);
            errorNotification.setText("User name and password didn't match!");


        } else if (uid == 0){
            this.setVisible(false);
            new Admin().setVisible(true);
        } else {
            System.err.println("UID: "+uid);
            subscribeJMS();
            this.setVisible(false);
            gl.setVisible(true);
        }
    }//GEN-LAST:event_logInButtonActionPerformed

    private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed
        new Register().setVisible(true);
    }//GEN-LAST:event_RegisterButtonActionPerformed


    private void subscribeJMS() {

        /*
         * Create a JNDI API InitialContext object if none exists
         * yet.
         */
        try {
            jndiContext = new InitialContext();
        } catch (NamingException e) {
            System.out.println("Could not create JNDI API " +
                "context: " + e.toString());
            e.printStackTrace();
            System.exit(1);
        }

        /*
         * Look up connection factory and topic.  If either does
         * not exist, exit.
         */
        try {
            topicConnectionFactory = (TopicConnectionFactory)
                jndiContext.lookup("jms/gameStateConnectionFactory");
            topic = (Topic) jndiContext.lookup("jms/gameStateTopic");
        } catch (NamingException e) {
            System.out.println("JNDI API lookup failed: " +
                e.toString());
            e.printStackTrace(System.err);
            System.exit(1);
        }

        /*
         * Create connection.
         * Create session from connection; false means session is
         * not transacted.
         * Create subscriber.
         * Register message listener (GameLobby).
         * Receive text messages from topic.
         * Close connection.
         */
        try {
            topicConnection =
                topicConnectionFactory.createTopicConnection();
            topicSession =
                topicConnection.createTopicSession(false,
                    Session.AUTO_ACKNOWLEDGE);
            topicSubscriber =
                topicSession.createSubscriber(topic);
            gl = new GameLobby();
            topicSubscriber.setMessageListener(gl);
            topicConnection.start();
        } catch (Exception e) {
            System.err.println("Exception occurred: " +
                e.toString());
            e.printStackTrace(System.err);
        }
    }

   public static void main(String[] args) throws NamingException {

       beanRemote = (NinetyNineGameBeanRemote) new InitialContext().lookup(
               "java:global/NinetyNineServer/NinetyNineGameBean");

       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               try {
                wp = new WelcomePage();
                wp.setVisible(true);
               } catch (NamingException e) {
                   e.printStackTrace(System.err);
               }
           }
       });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton RegisterButton;
    private javax.swing.JLabel errorNotification;
    private javax.swing.JButton logInButton;
    private javax.swing.JPanel loginPanel;
    private javax.swing.JLabel password;
    private javax.swing.JPasswordField passwordTextField;
    private javax.swing.JPanel registerPanel;
    private javax.swing.JTextField sloganTextField;
    private javax.swing.JLabel username;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables

}
